package me.zhengjie.config.thread

import me.zhengjie.common.utils.SpringContextHolder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import java.util.concurrent.Executor
import java.util.concurrent.ThreadPoolExecutor

/**
 * 创建自定义的线程池
 * @author Zheng Jie
 * @description
 * @date 2023-06-08
 */
@Configuration
class CustomExecutorConfig {

    /**
     * 自定义线程池，用法 @Async
     * @return Executor
     */
    @Bean
    @Primary
    fun elAsync(): Executor {
        val executor = ThreadPoolTaskExecutor()
        executor.corePoolSize = AsyncTaskProperties.corePoolSize
        executor.maxPoolSize = AsyncTaskProperties.maxPoolSize
        executor.queueCapacity = AsyncTaskProperties.queueCapacity
        executor.setThreadNamePrefix("el-async-")
        executor.keepAliveSeconds = AsyncTaskProperties.keepAliveSeconds
        executor.setRejectedExecutionHandler(ThreadPoolExecutor.CallerRunsPolicy())
        executor.initialize()
        return executor
    }

    /**
     * 自定义线程池，用法 @Async("otherAsync")
     * @return Executor
     */
    @Bean
    fun otherAsync(): Executor {
        val executor = ThreadPoolTaskExecutor()
        executor.corePoolSize = 15
        executor.queueCapacity = 50
        executor.keepAliveSeconds = AsyncTaskProperties.keepAliveSeconds
        executor.setThreadNamePrefix("el-task-")
        executor.setRejectedExecutionHandler(ThreadPoolExecutor.CallerRunsPolicy())
        executor.initialize()
        return executor
    }
}